package com.bjpowernode.manager;

import com.bjpowernode.constant.Constants;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 *
 */
@Component
public class RedisManager {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setValue(String key, String value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public void setValue(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public boolean removeValue(String key) {
        return redisTemplate.delete(key);
    }

    // @async异步执行注解
    @Async
    public void flushKeyExpire(String key, long timeout, TimeUnit unit) {
        redisTemplate.expire(key, timeout, unit);
    }

    // 获取数据缓存
    // lambda表达式 , 函数式接口
    public <T> List<T> getData(Supplier<List<T>> redisSupplier , Supplier<List<T>> databaseSupplier , Consumer<List<T>> databaseConsumer) {
        // 从redis中获取数据
        List<T> list = redisSupplier.get();
        // 判空
        if (CollectionUtils.isEmpty(list)) {
            // 空的 , 去数据库查 , 并将查询到的数据添加到存入redis
            list = databaseSupplier.get();
            // 判断数据库中是否拿到数据 , 如果拿到将数据存入redis
            if (!CollectionUtils.isEmpty(list)){
                // 非空
                databaseConsumer.accept(list);
            }
        }
        return list;
    }

    public long getOnlyNumber() {
        return redisTemplate.opsForValue().increment(Constants.REDIS_ONLY_NUMBER);
    }
}
